/*
* 后台页面登录
* */

const router = require('koa-router')();
const db = require('../dbs/user');
const log = require('../libs/log4js')('USERRouter');
const request = require('axios');
const md5 = require('md5-node');

router.post('/addUser', async (ctx) => {
  const req = ctx.request.body;
  log.debug('开始注册', req.userName);
  const isHaveUser = await db.getUserByUserName()[0] || false;
  if (isHaveUser) {
    ctx.body = JSON.stringify({
      code: 100,
      msg: '该用户已经注册',
    });
  } else {
    const user = await db.sigin({
      userName: req.userName,
      pwd: md5(req.pwd)
    });
    ctx.body = JSON.stringify({
      code: 200,
      data: 'suc',
      msg: '注册成功',
    });
  }
});

router.post('/login', async (ctx) => {
  const req = ctx.request.body;
  log.debug('开始登录', req.userName);
  let flag = await db.adminLogin(req.userName, req.pwd);
  if (!flag) {
    ctx.body = JSON.stringify({
      code: 100,
      msg: '账号或密码不正确',
    });
  } else {
    ctx.body = JSON.stringify({
      code: 200,
      data: flag.token,
      msg: 'suc',
    });
  }
});

module.exports = router;
